import time

from loguru import logger
from DrissionPage import Chromium
import pandas as pd
from read_search_file import get_search_comp, get_complete_sheet1

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)

def create_creative_func(creative_view_tab, r_excel, browser, file_path, unit_next_button_ele=None, log_callback=None):
    ## 读取转化组件sheet
    df_search_comp = get_search_comp(file_path)

    # creative_view_tab.wait.load_start()
    logger.info(f"进入创意界面")
    img_all_select = r_excel['封面全选']
    note_ids_arr = r_excel['笔记ID']
    indus_qualification = r_excel['行业资质']
    auto_optimize = r_excel['自动优化'] if pd.notna(r_excel['自动优化']) else "关闭"

    items = creative_view_tab.ele('css:.form-content > .group').eles('.item')

    for i, item in enumerate(items):
        item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称').scroll.to_center()
        creative_name_ele = item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=15)
        # creative_view_tab.wait.eles_loaded('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称')  # 等待元素加载

        current_note_id = item('css:.d-table__body > tr > td:nth-child(2)').text
        star_name = item('css:.d-table__body > tr > td:nth-child(4)').text

        if current_note_id not in note_ids_arr:
            log_message(log_callback, f"当前笔记ID:{current_note_id}-达人昵称:{star_name}在转化组件中没有匹配值, 默认转化组件选【无】", "red")

        creative_name_ele.input(star_name, clear=True)  # 填写创意名称

        # 处理监测链接
        for d in df_search_comp.itertuples():
            if current_note_id != d.笔记ID.strip():
                continue
            monitor_link = d.监测链接.strip()
            if pd.notna(monitor_link):
                if add_monitor_link := item('tag:div@@text()=添加监测链接', timeout=2):
                    add_monitor_link.wait(0.5).click(timeout=3)  # 点击添加监测链接

                    monitor_link_arr = monitor_link.strip().split('\n')
                    for monitor in monitor_link_arr:
                        creative_view_tab.ele('tag:span@@class=add-action@@text()= 添加 ').wait(0.5).click(timeout=3)  # 点击添加
                        creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().child().child(index=1).child().child('tag:input@@class=d-text@@placeholder=请输入链接').input(monitor, clear=True)  # 输入链接
                    # item('tag:input@@class=d-text@@placeholder=请输入链接').input(monitor_link, clear=True)  # 输入链接
                    creative_view_tab.ele('tag:span@@class=d-text --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click()  # 保存链接
                else:
                    if edit_monitor_link := item('tag:div@@text()=修改监测链接', timeout=2):
                        edit_monitor_link.wait(1).click(timeout=3)
                        creative_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入链接').input(monitor_link, clear=True)  # 输入链接
                        creative_view_tab.ele('tag:span@@class=d-text --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click()  # 保存链接
            break
        # 第一个标签页编辑投放资质之后绑定至所有创意
        if i == 0:
            item('tag:span@@class=link-text@@text()=编辑').wait(.5).run_js('this.click();')

            if creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2):
                logger.info("投放资质存在继续修改按钮")
                creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2).run_js('this.click();')

            # creative_view_tab.wait.eles_loaded('css:.d-select-input-filter > .d-text:nth-child(1)')
            quali_bottom_select_ele = creative_view_tab.ele('css:.d-select-input-filter > .d-text:nth-child(1)', timeout=2)
            if quali_bottom_select_ele:
                quali_bottom_select_ele.wait(0.3).run_js('this.click();') # 点击行业资质下拉框

            # 选中行业资质具体内容
            if indus_qualification_content_ele := creative_view_tab.ele(f'tag:div@@class=d-grid d-option d-option-content --color-text-title@@text():{indus_qualification}', timeout=2):
                indus_qualification_content_ele.wait(0.3).click(by_js=True)  # 选中具体资质内容
            else:
                creative_view_tab.ele('css:body > div.d-popover.d-popover-default.d-dropdown.--size-min-width-large > div > div > div > div > div:nth-child(1)', timeout=2).click(by_js=True)

            creative_view_tab.ele('tag:span@@text()= 绑定至所有创意 ').run_js('this.click();')  # 点击绑定当前创意

            if creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2):
                logger.info("投放资质存在确认修改按钮")
                creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2).run_js('this.click();')

        # 创意素材
        if img_all_select == '否':
            if item('tag:a@@text()=添加封面', timeout=0.5):
                item('tag:a@@text()=添加封面').scroll.to_center()
                item('tag:a@@text()=添加封面').click(by_js=True)
            if item('tag:a@@text()=选择封面', timeout=0.5):
                item('tag:a@@text()=选择封面').scroll.to_center()
                item('tag:a@@text()=选择封面').click(by_js=True)

            img_all_select_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')

            if len(img_all_select_eles) > 1:
                # creative_view_tab.wait.eles_loaded('tag:span@@text()=全选')
                creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
                creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
            else:
                creative_view_tab.ele('tag:span@@class=d-text --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 取消 ').click(by_js=True)

        item(f'tag:div@@class=flexible align-center@@text()={auto_optimize}').click(by_js=True)  # 自动优化

        ## 处理转化组件
        item(f'tag:span@@text()=转化组件').scroll.to_center()  # 滚到转化组件

        if not df_search_comp.empty:
            for s in df_search_comp.itertuples():
                if current_note_id != s.笔记ID.strip():
                    continue
                trans_comp = s.转化组件.strip()

                item(f'tag:span@@text()={trans_comp}').scroll.to_center()
                item(f'tag:span@@text()={trans_comp}').parent(1).click(by_js=True)  # 点击转化组件

                if trans_comp == '搜索组件':
                    item('tag:span@@text()=图片或视频底部').scroll.to_center()
                    img_or_video_ele = item('tag:span@@text()=图片或视频底部')
                    img_or_video_ele_str = img_or_video_ele.prev().prev().attr('class')
                    if 'unchecked' not in img_or_video_ele_str:
                        img_or_video_ele.parent(1).click(by_js=True)  # 先取消图片或视频底部默认选中

                    top_comment_ele = item('tag:span@@text()=置顶评论')
                    top_comment_ele_str = top_comment_ele.prev().prev().attr('class')
                    if 'unchecked' not in top_comment_ele_str:
                        top_comment_ele.parent(1).click(by_js=True)  # 先取消置顶评论默认选中

                    search_word = s.搜索词 if s.搜索词 else ""

                    comp_loc_arr = s.组件位置.strip().split('\n')  ## 组件位置
                    for comp in comp_loc_arr:
                        if comp == '图片或视频底部':
                            item('tag:span@@text()=图片或视频底部').parent(1).wait(0.5).click(by_js=True)  # 点击图片或视频底部
                            item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').input(search_word, clear=True)  # 点击图片或视频底部
                        if comp == '置顶评论':
                            item('tag:span@@text()=置顶评论').parent(1).wait(0.5).click(by_js=True)  # 点击置顶评论
                            item('css:.conversion-group > .input > .comment-input-box input[placeholder="请输入置顶评论文案"]').input(s.置顶评论文案, clear=True)  # 点击图片或视频底部
                            item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').input(search_word, clear=True)  # 点击图片或视频底部
                break

    creative_view_tab.ele('css:.footer-action .d-button:nth-child(2)').click(by_js=True)  # 点击创意层级完成
    if not item('tag:span@@class=error@@text():请选择组件的位置', timeout=1) and not item('tag:span@@class=error@@text():请填写搜索词', timeout=1) and not item('tag:span@@class=error@@text():请输入评论文案，默认项为必填', timeout=1):
        browser.close_tabs(creative_view_tab)
        logger.info(f"创意完成")

# if __name__ == '__main__':
#     file_path = "搜索-创建计划-样例.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/creativity/113881059/236135491/4/1/2?isStep=true&from=CampaignList&AFormGrayFlag=false&vSellerId=63be38f04ee9db000147041b')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_creative_func(unit_view_tab, row, browser, file_path, ['123', '122222'])
